class Solution {
    int ans = 0;

    public int divide(int dividend, int divisor) {
        // 考虑被除数为最小值的情况
        if (dividend == Integer.MIN_VALUE) {
            if (divisor == 1) {
                return Integer.MIN_VALUE;
            }
            if (divisor == -1) {
                return Integer.MAX_VALUE;
            }
        } // 考虑除数为最小值的情况
        if (divisor == Integer.MIN_VALUE) {
            return dividend == Integer.MIN_VALUE ? 1 : 0;
        } // 考虑被除数为 0 的情况
        if (dividend == 0) {
            return 0;
        }
        // 一般情况，使用类二分查找
        // 将所有的正数取相反数，这样就只需要考虑一种情况
        boolean rev = false;
        if (dividend > 0) {
            dividend = -dividend;
            rev = !rev;
        }
        if (divisor > 0) {
            divisor = -divisor;
            rev = !rev;
        }

        ans = 0;
        solve(dividend, divisor, 0);
        return rev ? -ans : ans;
    }

    public int solve(int dividend, int divisor, int candidate) {
        int temp = divisor << candidate;
        if (temp < dividend) {
            return dividend;
        }
        if (temp >= Integer.MIN_VALUE >> 1) {
            dividend = solve(dividend, divisor, candidate + 1);
        }
        if (temp >= dividend) {
            ans += 1 << candidate;
            dividend -= temp;
        }
        return dividend;
    }
}